﻿using System;
using System.IO;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.AppCode.Lib;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

namespace mojoPortal.Web.RS.SBM
{
    public partial class PreviewAdHocInvoice : Page
    {
        decimal _taxAmount;
        decimal _additionalFee;
        decimal _subTotal;
        decimal _additionalDiscount;
        decimal _balanceDue;

        string _invoiceNum;
        string _PONum;
        string _email;
        string _dueDate;
        string _additionalInstruction;
        string _terms;

        int _locationid;
        int _billcontactid;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                int invoiceid = 0;
                if (Request.QueryString["invoiceid"] != null)
                    invoiceid = Convert.ToInt32(Request.QueryString["invoiceid"].ToString());

                if (invoiceid > 0)
                {
                    RSUserIdentity userIdentity = new RSUserIdentity();
                    int workorderid = GetInvoiceDetailByID(userIdentity.RSCompanyId, invoiceid);
                    LoadWorkOrderList(userIdentity.RSCompanyId, workorderid);
                    txtFrom.Text = userIdentity.RSCompanyEmail;
                    txtSubject.Text = "Invoice";
                }
            }
        }
        protected void btnEmail_Click(object sender, EventArgs e)
        {
            divEmailFields.Visible = true;
            divButtons.Visible = false;
        }
        protected void btnSend_Click(object sender, EventArgs e)
        {
            //StringWriter sw = new StringWriter();
            //HtmlTextWriter htw = new HtmlTextWriter(sw);
            //repeatInvoiceList.RenderControl(htw);
            //string s = sw.GetStringBuilder().ToString();
            //divInvoice.Visible = false;
            //litPreview.Text = s;

            RSUserIdentity userIdentity = new RSUserIdentity();
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            repeatInvoiceList.RenderControl(htw);
            string body = sw.GetStringBuilder().ToString();
            string subject = txtSubject.Text;
            string toEmail = txtTo.Text;
            string fromEmail = txtFrom.Text;
            string ccEmail = txtCC.Text;
            if (fromEmail.Length > 0 && toEmail.Length > 0)
            {
                RSCommonFunctions.SendEmail(body, subject, fromEmail, toEmail, ccEmail);
                lblMessage.Text = "Email Successfully Sent.";
                divButtons.Visible = false;
                divEmailFields.Visible = false;
            }
        }

        private void LoadWorkOrderList(int companyid, int workorderid)
        {
            SqlCommand myCommand;
            SqlDataReader myDataReader;
            String strSQL = "SELECT workorderid,companyid,quantity, workordername as description,rate,LaborCost FROM vw_WorkOrderInvoiceItem WHERE companyid=@companyid AND workorderid=@workorderid";
            SqlParameter param;
            SqlConnection myConnection;

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[RSCommonFunctions.GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(strSQL, myConnection);
            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@workorderid";
            param.Value = workorderid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            repeatInvoiceList.DataSource = myDataReader;
            repeatInvoiceList.DataBind();
            myConnection.Close();
        }
        public int GetInvoiceDetailByID(int companyid, int invoiceid)
        {
            int workorderid = 0;
            String strSQL = "select * from vw_workorderinvoice where companyid=@companyid and invoiceid=@invoiceid";
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;
            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[RSCommonFunctions.GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(strSQL, myConnection);
            SqlDataReader myDataReader;

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@invoiceid";
            param.Value = invoiceid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

            if (myDataReader.HasRows)
            {
                myDataReader.Read();
                _invoiceNum = myDataReader["InvoiceNo"].ToString();
                _PONum = myDataReader["PONumber"].ToString();
                _email = myDataReader["Email"].ToString();
                txtTo.Text = _email;

                if (myDataReader["DueDt"] != DBNull.Value)
                {
                    DateTime duedt = Convert.ToDateTime(myDataReader["DueDt"].ToString());
                    _dueDate = duedt.ToShortDateString();
                }

                _additionalInstruction = myDataReader["AdditionalInstructions"].ToString();
                _terms = myDataReader["Terms"].ToString();

                _locationid = Convert.ToInt32(myDataReader["LocationId"].ToString());
                _billcontactid = Convert.ToInt32(myDataReader["BillingContactId"].ToString());


                workorderid = Convert.ToInt32(myDataReader["WorkOrderId"].ToString());

                _taxAmount = Convert.ToDecimal(myDataReader["TaxAmount_CF"].ToString());
                _additionalFee = Convert.ToDecimal(myDataReader["AdditionalFeeAmount"].ToString());
                _subTotal = Convert.ToDecimal(myDataReader["SubTotal"].ToString());
                _additionalDiscount = Convert.ToDecimal(myDataReader["AdditionalDiscountAmount"].ToString());
                _balanceDue = Convert.ToDecimal(myDataReader["BalanceDue_CF"].ToString());
            }
            myConnection.Close();

            return workorderid;
        }

        protected void repeatInvoiceList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Header)
            {
                RSUserIdentity userIdentity = new RSUserIdentity();

                Label lblInvoiceNum = (Label)e.Item.FindControl("lblInvoiceNum");
                lblInvoiceNum.Text = _invoiceNum;

                Label lblPONum = (Label)e.Item.FindControl("lblPONum");
                lblPONum.Text = _PONum;

                Label lblDueDate = (Label)e.Item.FindControl("lblDueDate");
                lblDueDate.Text = _dueDate;

                Label lblAdditionalInstruction = (Label)e.Item.FindControl("lblAdditionalInstruction");
                lblAdditionalInstruction.Text = _additionalInstruction;

                Label lblTerms = (Label)e.Item.FindControl("lblTerms");
                lblTerms.Text = _terms;

                Label lblJobAddress = (Label)e.Item.FindControl("lblJobAddress");
                lblJobAddress.Text = RSSBMCommonFunctions.GetLocationFullAddressByID(userIdentity.RSCompanyId, _locationid);

                Label lblBillingContact = (Label)e.Item.FindControl("lblBillingContact");
                lblBillingContact.Text = RSSBMCommonFunctions.GetContactFullNameByID(userIdentity.RSCompanyId, _billcontactid);

                Label lblBillingAddress = (Label)e.Item.FindControl("lblBillingAddress");
                lblBillingAddress.Text = RSSBMCommonFunctions.GetBillingLocationFullAddress(userIdentity.RSCompanyId, _billcontactid);

                Label lblCompanyName = (Label)e.Item.FindControl("lblCompanyName");
                lblCompanyName.Text = userIdentity.RSCompanyName;

                Literal litCompanyFullAddress = (Literal)e.Item.FindControl("litCompanyFullAddress");
                litCompanyFullAddress.Text = "<b>" + RSCommonFunctions.GetCompanyFullAddress(userIdentity.RSCompanyId) + "</b>";

                if (Convert.ToInt32(_balanceDue) == 0)
                {
                    Image imgPaid = (Image)e.Item.FindControl("imgPaid");
                    imgPaid.Visible = true;
                }
            }
            if (e.Item.ItemType == ListItemType.Footer)
            {
                RSUserIdentity userIdentity = new RSUserIdentity();
                Label lblTaxAmount = (Label)e.Item.FindControl("lblTaxAmount");
                lblTaxAmount.Text = _taxAmount.ToString();

                Label lblAdditionalFee = (Label)e.Item.FindControl("lblAdditionalFee");
                lblAdditionalFee.Text = _additionalFee.ToString();

                Label lblSubTotal = (Label)e.Item.FindControl("lblSubTotal");
                lblSubTotal.Text = _subTotal.ToString();

                Label lblAdditionalDiscount = (Label)e.Item.FindControl("lblAdditionalDiscount");
                lblAdditionalDiscount.Text = _additionalDiscount.ToString();

                Label lblBalanceDue = (Label)e.Item.FindControl("lblBalanceDue");
                lblBalanceDue.Text = _balanceDue.ToString();
            }
        }

        //private void SendEmail(string body, string subject, string fromEmail, string toEmail, string ccEmail = "")
        //{
        //    System.Net.Mail.MailMessage eMail = new System.Net.Mail.MailMessage();
        //    eMail.IsBodyHtml = true;
        //    eMail.Body = body;
        //    eMail.From = new System.Net.Mail.MailAddress(fromEmail);
        //    eMail.To.Add(toEmail);
        //    if(ccEmail.Length > 0)
        //        eMail.CC.Add(ccEmail);
        //    eMail.Subject = subject;
        //    System.Net.Mail.SmtpClient SMTP = new System.Net.Mail.SmtpClient();

        //    string smtpUserName = ConfigurationManager.AppSettings["SMTPUser"].ToString();
        //    string smtpPassword = ConfigurationManager.AppSettings["SMTPPassword"].ToString();
        //    string smtpServer = ConfigurationManager.AppSettings["SMTPServer"].ToString();
        //    SMTP.Credentials = new System.Net.NetworkCredential(smtpUserName, smtpPassword);
        //    SMTP.Host = smtpServer;
        //    SMTP.Send(eMail);
        //    eMail.Dispose();
        //}

        protected void btnPrint_Click(object sender, EventArgs e)
        {
            divEmailFields.Visible = false;
            divButtons.Visible = false;

            String csname = "PrintPageScript";
            if (!ClientScript.IsClientScriptBlockRegistered(csname))
            {
                String cstext = "<script type=\"text/javascript\">window.print();</script>";
                ClientScript.RegisterStartupScript(this.GetType(), csname, cstext);
            }

        }
    }
}